package com.luncheng.mcp.core.strategy;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.luncheng.mcp.core.client.HttpClientSseClientTransport;
import com.luncheng.mcp.core.model.McpClientConfig;
import com.luncheng.mcp.core.model.McpServerConfig;
import io.modelcontextprotocol.server.transport.WebMvcSseServerTransportProvider;
import io.modelcontextprotocol.spec.McpClientTransport;
import io.modelcontextprotocol.spec.McpServerTransportProvider;
import org.springframework.util.CollectionUtils;

import java.net.http.HttpRequest;

public class SseTransportStrategy implements TransportStrategy {
    @Override
    public McpClientTransport createClientTransport(McpClientConfig mcpClientConfig) {
        HttpRequest.Builder requestBuilder = HttpRequest.newBuilder();
        if (!CollectionUtils.isEmpty(mcpClientConfig.getParams())) {
            mcpClientConfig.getParams().forEach(requestBuilder::header);
        }
        return HttpClientSseClientTransport.builder(mcpClientConfig.getServerHost())
                .sseEndpoint(mcpClientConfig.getSseEndpoint())
                .params(mcpClientConfig.getParams())
                .headers(mcpClientConfig.getHeaders())
                .objectMapper(new ObjectMapper())
                .build();
    }

    @Override
    public McpServerTransportProvider createServerTransport(ObjectMapper objectMapper, McpServerConfig config) {
        return new WebMvcSseServerTransportProvider(objectMapper, config.getMessageEndpoint(), config.getSseEndpoint());
    }
}